package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) throws Exception {
        // 1.查询自媒体文章是否存在
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        // 2.提取文章的文本和图片信息
        Map<String, Object> textAndImages = handleTextAndImages(wmNews);

        // 2.5.自定义敏感词审核
        boolean isSensitiveScan = handleSensitiveScan(textAndImages.get("content").toString(), wmNews);
        if (!isSensitiveScan) return;

        // 3.调用阿里云审核文本
        boolean isTextScan = handleTextScan(textAndImages.get("content").toString(), wmNews);
        if (!isTextScan) return;

        // 4.调用阿里云审核图片
        boolean isImageSacn = handleImageScan((List<String>) textAndImages.get("images"), wmNews);
        if (!isImageSacn) return;

        // 5.审核成功,将文章数据保存到用户端
        ResponseResult responseResult = saveAPPArticle(wmNews);
        if (!responseResult.getCode().equals(200)) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }

        //=====================自定义异常=============================
        // int a = 1/0;
        //==========================================================

        // 保存文章后需要回填文章id并修改文章状态
        wmNews.setArticleId((Long) responseResult.getData());
        updateWmNews(wmNews, (short) 9, "审核成功");

    }

    /**
     * 自定义敏感词审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        // 1.获取自定义敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers
                .<WmSensitive>lambdaQuery()
                .select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream()
                .map(WmSensitive::getSensitives)
                .collect(Collectors.toList());

        // 2.初始化敏感词词库
        SensitiveWordUtil.initMap(sensitiveList);

        // 3.匹配敏感词关键字
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);

        // 4.判断
        if (map.size() > 0) {
            // 当前文本含有敏感词,修改文章状态
            updateWmNews(wmNews, (short) 2, "当前文章中出现违规内容" + map);
            flag = false;
        }

        return flag;
    }

    /**
     * 保存app端的文章数据
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveAPPArticle(WmNews wmNews) throws Exception {
        /*// 拷贝
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);

        // 补充属性
        // 作者id和名称
        dto.setAuthorId(wmNews.getUserId());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        // 文章布局
        dto.setLayout(wmNews.getType());

        // 频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        // 文章id(考虑修改文章情况)
        if (wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }*/

        // 使用构建者模式,方便以后维护,适合构建复杂对象
        ArticleDtoBuilder articleDtoBuilder = new ArticleDtoBuilder(wmNews, wmChannelMapper, wmUserMapper);
        ArticleDto articleDto = articleDtoBuilder.buildBeanCopy()
                .buildAuthor()
                .buildChannel()
                .buildBasic()
                .builder();

        ResponseResult responseResult = articleClient.saveArticle(articleDto);

        return responseResult;
    }

    /**
     * 审核文章中的图片内容
     *
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        boolean flag = true;
        // 如果文章中不含图片则直接通过
        if (images == null || images.size() == 0) {
            return flag;
        }
        // 从minio下载图片
        // 图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        // 下载
        List<byte[]> list = new ArrayList<>();
        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);

            // 图片识别文字审核--begin
            // 将byte[]转成bufferedImage
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BufferedImage imageFile = ImageIO.read(inputStream);

            // 获取图片中的文字
            String result = tess4jClient.doOCR(imageFile);

            // 审核图片中的文字是否包含敏感词
            boolean isSensitive = handleSensitiveScan(result, wmNews);

            // 审核失败,返回false
            if (!isSensitive) return false;

            // 图片识别文字审核--begin

            list.add(bytes);
        }


        // 审核图片
        Map map = greenImageScan.imageScan(list);
        if (map != null) {
            if (map.get("suggestion").equals("block")) {
                // 审核失败
                flag = false;
                // 更新文章状态
                updateWmNews(wmNews, (short) 2, "当前文章存在违规内容");
            }
            if (map.get("suggestion").equals("review")) {
                // 转人工审核
                flag = false;
                // 更新文章状态
                updateWmNews(wmNews, (short) 3, "当前文章存在不确定内容");
            }
        }
        return flag;
    }

    /**
     * 审核文章中的文本内容
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) throws Exception {
        boolean flag = true;
        Map map = greenTextScan.greeTextScan(wmNews.getTitle() + "-" + content);
        if (map != null) {
            if (map.get("suggestion").equals("block")) {
                // 审核失败
                flag = false;
                // 更新文章状态
                updateWmNews(wmNews, (short) 2, "当前文章存在违规内容");
            }
            if (map.get("suggestion").equals("review")) {
                // 转人工审核
                flag = false;
                // 更新文章状态
                updateWmNews(wmNews, (short) 3, "当前文章存在不确定内容");
            }
        }
        return flag;
    }

    /**
     * 修改文章状态
     *
     * @param wmNews
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        // 设置文章状态
        wmNews.setStatus(status);
        // 设置拒绝理由
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 抽取文章中的文本和图片数据
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // 存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();
        // 存储图片信息
        List<String> images = new ArrayList();

        String content = wmNews.getContent();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("text")) {
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")) {
                images.add(map.get("value").toString());
            }
        }
        Map<String, Object> textAndImagesMap = new HashMap<>();
        textAndImagesMap.put("content", stringBuilder);
        textAndImagesMap.put("images", images);

        return textAndImagesMap;
    }
}
